package com.rzjm.exercise.module.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rzjm.exercise.common.base.controller.BaseController;
import com.rzjm.exercise.common.base.data.DataTableLayUI;
import com.rzjm.exercise.common.log.annotation.Log;
import com.rzjm.exercise.common.utils.*;
import com.rzjm.exercise.module.domain.*;
import com.rzjm.exercise.module.domain.dto.Cone;
import com.rzjm.exercise.module.domain.dto.Cylinder;
import com.rzjm.exercise.module.domain.dto.Rect;
import com.rzjm.exercise.module.service.*;
import com.rzjm.exercise.sys.system.user.domain.UserDO;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/**
 *  筒仓测距设备
 *
 * @author mr.zhou
 * @email zhouwei_nice@163.com
 * @date 2020-12-15 22:36:23
 */
@Controller
@RequestMapping("/module/device/range")
public class DeviceRangeController extends BaseController {
    @Resource
    private DeviceRangeService deviceRangeService;
    @Resource
    private DeviceRangeRecordService deviceRangeRecordService;
    @Resource
    private DeviceRangeResultService deviceRangeResultService;
    @Resource
    private ShopService shopService;
    @Resource
    private WxUserService wxUserService;


    @Value("${projecturl.uploadPath}")
    private String uploadPath;

    @Log("查询设备页面")
    @GetMapping("/shop/list")
    @RequiresPermissions("module:deviceRange:deviceRange")
    String shopList(Model model) {
        model.addAttribute("shopType",5);
        model.addAttribute("deviceType",0);//   0 - 测量仓  1 - 测油罐
        return "module/device/range/shop";
    }


    @Log("查询设备页面")
    @GetMapping("/shop/list/{deviceType}")
    @RequiresPermissions("module:deviceRange:deviceRange")
    String shopList1(Model model,@PathVariable("deviceType") Integer deviceType) {
        model.addAttribute("shopType",5);
        model.addAttribute("deviceType",deviceType);//   0 - 测量仓  1 - 测油罐
        return "module/device/range/shop";
    }

    @Log("查询设备页面")
    @GetMapping("/{shopId}")
    @RequiresPermissions("module:deviceRange:deviceRange")
    String deviceList(Model model,@PathVariable("shopId") Integer shopId) {
        model.addAttribute("shopId",shopId);
        return "module/device/range/range";
    }

    @Log("查询设备页面")
    @GetMapping("/{shopId}/{deviceType}")
    @RequiresPermissions("module:deviceRange:deviceRange")
    String deviceList(Model model,@PathVariable("shopId") Integer shopId,@PathVariable("deviceType") Integer deviceType) {
        model.addAttribute("shopId",shopId);
        model.addAttribute("deviceType",deviceType);//   0 - 测量仓  1 - 测油罐

        UserDO user = getUser();
        model.addAttribute("is_shop",0);
        if(user.getUserType() == 4 || user.getUserType() == 6){
            model.addAttribute("is_shop", 1);
        }
        return "module/device/range/range";
    }

    @Log("查询设备页面")
    @GetMapping("/manager/{shopId}/{deviceType}")
    @RequiresPermissions("module:deviceRange:deviceRange")
    String deviceListManager(Model model,@PathVariable("shopId") Integer shopId,@PathVariable("deviceType") Integer deviceType) {
        model.addAttribute("shopId",shopId);
        model.addAttribute("deviceType",deviceType);//   0 - 测量仓  1 - 测油罐

        Shop shop = shopService.findById(shopId);
        if(shop != null){
            model.addAttribute("shop",shop);
        }

//                比例
        model.addAttribute("heightRate", 0);
        model.addAttribute("deviceHeight", 0);
        QueryWrapper<DeviceRange> qw = new QueryWrapper<>();
        qw.eq("shop_id",shopId);
        qw.eq("device_type",deviceType);
        qw.orderByAsc("device_name");
        List<DeviceRange> ranges = deviceRangeService.list(qw);

        if(ranges.size() > 0){
            DeviceRange range = ranges.get(0);
            if(range!= null){
                range.setTotalWeight(MathUtil.getDouble(range.getTotalWeight() / 1000));
                if(range.getHumidity().equals("0") || range.getHumidity().equals("00") || Double.parseDouble(range.getTemperature()) > 100){
                    range.setTemperature(MathUtil.getDouble(Double.parseDouble(range.getTemperature()) * 0.1) + "");
                }
                if(range.getLastVolumeNew() < 0){
                    range.setLastVolumeNew(0d);
                }
            }

            model.addAttribute("deviceStr", JSONUtil.toJsonStr(range));
            model.addAttribute("device", range);

            QueryWrapper<DeviceRangeResult> qwResult = new QueryWrapper<>();
            qwResult.eq("device_id",range.getId());
            qwResult.orderByDesc("create_time");
            qwResult.last("limit 1");
            DeviceRangeResult lastResult = deviceRangeResultService.getOne(qwResult);
            if(lastResult!= null){
                double deviceHeight = lastResult.getHeight();
                if(deviceHeight < 0){
                    deviceHeight = 0;
                }
                model.addAttribute("lastHeight", lastResult.getHeight());

//                double height = 0;
//                if(deviceType == 0){
//                    height = MathUtil.getDouble(range.getCylinderHeight() - deviceHeight);
//                }else{
//                }
//                height = deviceHeight;

                double height = 0;
                if(range.getDeviceType() == 0){
                    height = MathUtil.getDouble(range.getCylinderHeight() - deviceHeight);
                }else{
                    height = deviceHeight;
                }


                System.out.println("高度height： " + height);
                System.out.println("高度总高度： " + range.getCylinderHeight());

                double heightRate = MathUtil.getDouble(height / range.getCylinderHeight());

                System.out.println("比例： " + heightRate);

                if(height < 0){
                    height = 0;
                }

                model.addAttribute("deviceHeight", height);
//                比例
                model.addAttribute("heightRate", heightRate);

            }
        }

        model.addAttribute("rangeCount",ranges.size());
        model.addAttribute("ranges",ranges);
        return "module/device/range/manager";
    }

    @Log("设备详情页面")
    @ResponseBody
    @GetMapping("/detail/{deviceId}")
    @RequiresPermissions("module:deviceRange:deviceRange")
    R deviceDetail(@PathVariable("deviceId") Integer deviceId) {
        Map<String,Object> map = new HashMap<>();
        DeviceRange device = deviceRangeService.findById(deviceId);
        if(device!= null){

            device.setTotalWeight(MathUtil.getDouble(device.getTotalWeight() / 1000));
            if(device.getHumidity().equals("0") || device.getHumidity().equals("00") || Double.parseDouble(device.getTemperature()) > 100){
                device.setTemperature(MathUtil.getDouble(Double.parseDouble(device.getTemperature()) * 0.1) + "");
            }
            if(device.getLastVolumeNew() < 0){
                device.setLastVolumeNew(0d);
            }

            map.put("deviceStr", JSONUtil.toJsonStr(device));
            map.put("device", device);

            map.put("deviceHeight", 0);
            map.put("heightRate", 0);

            QueryWrapper<DeviceRangeResult> qw = new QueryWrapper<>();
            qw.eq("device_id",deviceId);
            qw.orderByDesc("create_time");
            qw.last("limit 1");
            DeviceRangeResult lastResult = deviceRangeResultService.getOne(qw);
            if(lastResult!= null){

                double deviceHeight = lastResult.getHeight();
                if(deviceHeight < 0){
                    deviceHeight = 0;
                }

                System.out.println("筒仓总高度： cylinderHeight = " + device.getCylinderHeight());
                System.out.println("最后测量高度： deviceHeight = " + deviceHeight);

                double height = 0;
                if(device.getDeviceType() == 0){
                    height = MathUtil.getDouble(device.getCylinderHeight() - deviceHeight);
                }else{
                    height = deviceHeight;
                }
                System.out.println("高度height：  = " + height);

                double heightRate = MathUtil.getDouble(height / device.getCylinderHeight());
                System.out.println("比例： heightRate = " + heightRate);

//                比例
                map.put("heightRate", heightRate);

                if(height < 0){
                    height = 0;
                }
                map.put("deviceHeight", height);

            }
        }
        return R.ok(map);
    }


    @Log("查询设备")
    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("module:deviceRange:deviceRange")
    public DataTableLayUI<DeviceRange> list(DataTableLayUI<DeviceRange> condition) {

        Map<String,Object> map = condition.getSearchParams();

        String keyword = null;
        if(map != null) {
            keyword = StrUtil.isNotEmpty(map.get("search_like_keyword").toString()) ? map.get("search_like_keyword").toString():null;
        }
        Integer shopId = StrUtil.isNotEmpty(map.get("search_eq_shopId").toString()) ? Integer.parseInt(map.get("search_eq_shopId").toString()):null;

        Integer deviceType = StrUtil.isNotEmpty(map.get("search_eq_deviceType").toString()) ? Integer.parseInt(map.get("search_eq_deviceType").toString()):null;


        Map<String,Object> map1 = new HashMap<>();
        if(keyword != null){
            map1.put("device_num",keyword);
        }
        if(shopId!=null){
            map1.put("shop_id", shopId);
        }
        if(deviceType!=null){
            map1.put("device_type", deviceType);
        }

        Page<DeviceRange> page = deviceRangeService.getPage(condition);
        List<DeviceRange> list = deviceRangeService.getPageList(page,map1);

        DataTableLayUI<DeviceRange> dt = deviceRangeService.pageSearchCustom(page,list,condition);
        List<DeviceRange> devices = dt.getData();
        for (DeviceRange device : devices){
            Shop shop = shopService.findById(device.getShopId());
            if(shop!=null){
                device.setShopName(shop.getShopName());
            }

            double totalWeight = MathUtil.getDouble(device.getTotalWeight() / 1000);
            device.setTotalWeight(totalWeight);
        }
        return dt;
    }

    @Log("新增设备页面")
    @GetMapping("/add/{shopId}/{deviceType}")
    @RequiresPermissions("module:deviceRange:add")
    String add(Model model,@PathVariable("shopId") Integer shopId,@PathVariable("deviceType") Integer deviceType) {
        DeviceRange device = new DeviceRange();
        device.setShopId(shopId);
        device.setDeviceType(deviceType);
        device.setErrorHeight(4d);
        model.addAttribute("device", device);

        QueryWrapper<Shop> qw = new QueryWrapper<>();
        qw.eq("state",1);
//        qw.eq("shop_type",5);
        List<Shop> shops = shopService.list(qw);
        model.addAttribute("shops", shops);
        return "module/device/range/detail";
    }

    @Log("编辑设备页面")
    @GetMapping("/edit/{id}")
    @RequiresPermissions("module:deviceRange:edit")
    String edit(@PathVariable("id") Integer id, Model model) {
        DeviceRange device = deviceRangeService.findById(id);
        model.addAttribute("device", device);

        UserDO user = getUser();

        model.addAttribute("is_shop",0);
        if(user.getUserType() == 4 || user.getUserType() == 6){
            model.addAttribute("is_shop", 1);
        }

        QueryWrapper<Shop> qw = new QueryWrapper<>();
        qw.eq("state",1);
//        qw.eq("shop_type",5);
        List<Shop> shops = shopService.list(qw);
        model.addAttribute("shops", shops);

        if(user.getUserType() == 4 || user.getUserType() == 6){
            return "module/device/range/shopDetail";
        }
        return "module/device/range/detail";

    }

    /**
     * 保存
     */
    @Log("新增设备")
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("module:deviceRange:add")
    public R save(@Valid DeviceRange deviceRange) {
        DeviceRange deviceRange1 = deviceRangeService.selectByUniqueColumn("device_num",deviceRange.getDeviceNum());
        if(deviceRange1 != null){
            return R.error("该设备编号已存在");
        }
        double volumeCone = 0d;
        double volumeCylinder = 0d;

        if(deviceRange.getIsEllipse() == 2){//四方柱筒仓

            Rect rect = new Rect();
            rect.setLength(deviceRange.getRectLength());
            rect.setWidth(deviceRange.getRectWidth());
            rect.setHeight(deviceRange.getCylinderHeight());
            volumeCylinder = rect.volume();
            System.out.println("四方柱筒仓体积 = " + volumeCylinder);

            Cone cone = new Cone();
            cone.setIsEllipse(2);
            cone.setRectWidth(deviceRange.getRectWidth());
            cone.setRectLength(deviceRange.getRectLength());
            cone.setHeight(deviceRange.getConeHeight());
            volumeCone = cone.volume();
            System.out.println("四方锥体体积 = " + volumeCone);

        }else{//圆柱形 筒仓
            //创建圆柱体对象
            Cylinder volu = new Cylinder();
            //给半径和高赋值
            volu.setRad(deviceRange.getStoreDiameter() / 2);
            volu.setHeight(deviceRange.getCylinderHeight());
            //输出
            System.out.println("底面半径 = " + volu.getRad());
            System.out.println("圆柱的高 = " + volu.getHeight());
            System.out.println("圆柱");
            //调用方法直接输出底面积
            volu.area();
            volumeCylinder = volu.volume();

            //调用方法输出圆柱体体积
            System.out.println("圆柱体体积 = " + volumeCylinder);
            deviceRange.setMaxCylinderVolume(volumeCylinder);

            deviceRange.setLongHalfShaft(0d);
            deviceRange.setShortHalfShaft(0d);

            Cone cone = new Cone();
            cone.setIsEllipse(deviceRange.getIsEllipse());
            cone.setLongHalf(0);
            cone.setShortHalf(0);
            if(deviceRange.getIsEllipse() == 1){
                cone.setLongHalf(deviceRange.getLongHalfShaft());
                cone.setShortHalf(deviceRange.getShortHalfShaft());
            }
            cone.setRad(deviceRange.getStoreDiameter() / 2);
            cone.setHeight(deviceRange.getConeHeight());

            volumeCone = cone.volume();
            System.out.println("圆锥体体积 = " + volumeCone);
        }


        deviceRange.setMaxConeVolume(volumeCone);

        deviceRange.setMaxVolume(volumeCylinder + volumeCone);

        deviceRange.setStoreHeight(deviceRange.getConeHeight() + deviceRange.getCylinderHeight());
        deviceRange.setLastVolume(0d);
        deviceRange.setLastVolumeNew(0d);
        deviceRange.setState(1);
        deviceRange.setStoreState(0);
        deviceRange.setSort(1);
        deviceRange.setHeightDifference(1d);
        deviceRange.setConcaveConvexVolume(0d);
        deviceRange.setLastEmptyVolume(0d);
        deviceRange.setOnlineState(0);
        deviceRange.setTemperature("0");
        deviceRange.setHumidity("0");
        deviceRange.setErrorAngle(0);
//        deviceRange.setErrorHeight(4d);
        deviceRange.setExtendRatio(0d);
        deviceRange.setTotalWeight(0d);
        deviceRange.setAvgHeight(0d);
        deviceRange.setLastBevel(0d);
        deviceRange.setShapeType(0);
        deviceRange.setEmptyHeight(0.5);
        deviceRange.setCreateTime(new Date());

        /**
         * 凸起时 调整的重量
         */
        deviceRange.setBulgeKg(0d);

        /**
         * 凹下时 调整的重量
         */
        deviceRange.setConcaveKg(0d);
        if(deviceRange.getDeviceType() == 0){
            deviceRange.setConcaveKg(-5000d);
        }
        /**
         * 筒仓直径  deviceRange.getStoreDiameter()
         */
        //圆锥的 直角的角度
        double coneAngle = MathUtil.getAngleByHeightAndAngle(deviceRange.getConeHeight(),deviceRange.getStoreDiameter()/2);

        //圆锥的 直角的角度 * 2 = 完整的角度
        deviceRange.setConeAngle(coneAngle * 2);

        //斜边长度
        double coneHypotenuse = MathUtil.getHypotenuseFromLength(deviceRange.getConeHeight(),deviceRange.getStoreDiameter()/2);
        deviceRange.setConeHypotenuse(coneHypotenuse);

        if (deviceRangeService.save(deviceRange)) {
            return R.ok();
        }
        return R.error();
    }

    /**
     * 修改
     */
    @Log("更新设备")
    @ResponseBody
    @RequestMapping("/update")
    @RequiresPermissions("module:deviceRange:edit")
    public R update(@Valid DeviceRange deviceRange) {
        UserDO sysUser = getUser();
        if(sysUser.getUserType() == 0 || sysUser.getUserType() == 1){
            double volumeCone = 0d;
            double volumeCylinder = 0d;

            if(deviceRange.getIsEllipse() == 2){//四方柱筒仓

                Rect rect = new Rect();
                rect.setLength(deviceRange.getRectLength());
                rect.setWidth(deviceRange.getRectWidth());
                rect.setHeight(deviceRange.getCylinderHeight());
                volumeCylinder = rect.volume();
                System.out.println("四方柱筒仓体积 = " + volumeCylinder);

                Cone cone = new Cone();
                cone.setIsEllipse(2);
                cone.setRectWidth(deviceRange.getRectWidth());
                cone.setRectLength(deviceRange.getRectLength());
                cone.setHeight(deviceRange.getConeHeight());
                volumeCone = cone.volume();
                System.out.println("四方锥体体积 = " + volumeCone);

            }else{//圆柱形 筒仓
                //创建圆柱体对象
                Cylinder volu = new Cylinder();
                //给半径和高赋值
                volu.setRad(deviceRange.getStoreDiameter() / 2);
                volu.setHeight(deviceRange.getCylinderHeight());
                //输出
                System.out.println("底面半径 = " + volu.getRad());
                System.out.println("圆柱的高 = " + volu.getHeight());
                System.out.println("圆柱");
                //调用方法直接输出底面积
                volu.area();
                volumeCylinder = volu.volume();

                //调用方法输出圆柱体体积
                System.out.println("圆柱体体积 = " + volumeCylinder);
                deviceRange.setMaxCylinderVolume(volumeCylinder);

                deviceRange.setLongHalfShaft(0d);
                deviceRange.setShortHalfShaft(0d);

                Cone cone = new Cone();
                cone.setIsEllipse(deviceRange.getIsEllipse());
                cone.setLongHalf(0);
                cone.setShortHalf(0);
                if(deviceRange.getIsEllipse() == 1){
                    cone.setLongHalf(deviceRange.getLongHalfShaft());
                    cone.setShortHalf(deviceRange.getShortHalfShaft());
                }
                cone.setRad(deviceRange.getStoreDiameter() / 2);
                cone.setHeight(deviceRange.getConeHeight());

                volumeCone = cone.volume();
                System.out.println("圆锥体体积 = " + volumeCone);
            }

            deviceRange.setMaxConeVolume(volumeCone);

            deviceRange.setMaxVolume(volumeCylinder + volumeCone);

            deviceRange.setStoreHeight(deviceRange.getConeHeight() + deviceRange.getCylinderHeight());

            /**
             * 筒仓直径  deviceRange.getStoreDiameter()
             */
            //圆锥的 直角的角度
            double coneAngle = MathUtil.getAngleByHeightAndAngle(deviceRange.getConeHeight(),deviceRange.getStoreDiameter()/2);

            //圆锥的 直角的角度 * 2 = 完整的角度
            deviceRange.setConeAngle(coneAngle * 2);

            //斜边长度
            double coneHypotenuse = MathUtil.getHypotenuseFromLength(deviceRange.getConeHeight(),deviceRange.getStoreDiameter()/2);
            deviceRange.setConeHypotenuse(coneHypotenuse);
        }

        boolean bl = deviceRangeService.updateById(deviceRange);
        if(bl){
            OkHttpClientUtil.getInstance().getData("https://en.zcchengyi.com/ckapi/device/reset/range/redis/" + deviceRange.getId());
            return R.ok();
        }
        return R.error();
    }

    /**
     * 删除
     */
    @Log("删除设备")
    @PostMapping("/remove")
    @ResponseBody
    @RequiresPermissions("module:deviceRange:remove")
    public R remove( Integer id) {
        if (deviceRangeService.removeById(id)) {
            return R.ok();
        }
        return R.error();
    }


    @Log("新增设备页面")
    @GetMapping("/charts/{id}")
    String charts(@PathVariable("id") Integer id, Model model) {

        UserDO user = getUser();
        QueryWrapper<WxUser> qwUser = new QueryWrapper<>();
        qwUser.eq("sys_user_id",user.getUserId());
        qwUser.eq("platform", "cy");
        qwUser.last("limit 1");
        WxUser wxUser = wxUserService.getOne(qwUser);

        DeviceRange device = deviceRangeService.findById(id);
        if(device != null){
            Map<String,Object> mapReturn = deviceRangeRecordService.getChartData(wxUser,device);
            model.addAttribute("charts", mapReturn);
        }
        model.addAttribute("device", device);
        return "module/device/range/charts";
    }


    @Log("新增设备页面")
    @GetMapping("/charts3d/{id}")
    String charts3d(@PathVariable("id") Integer id, Model model) {
        DeviceRangeResult result = deviceRangeResultService.findById(id);
        if(result !=null) {
            DeviceRange deviceRange = deviceRangeService.findById(result.getDeviceId());
            model.addAttribute("device", deviceRange);
        }
        model.addAttribute("result", result);
        return "module/device/range/charts3d";
    }

    @Log("新增设备页面")
    @PostMapping("/charts/data")
    @ResponseBody
    R chartsData(@RequestParam Map<String,Object> paramJson) {
        int deviceId = Integer.parseInt(paramJson.get("deviceId").toString());

        UserDO user = getUser();
        QueryWrapper<WxUser> qwUser = new QueryWrapper<>();
        qwUser.eq("sys_user_id",user.getUserId());
        qwUser.eq("platform", "cy");
        qwUser.last("limit 1");
        WxUser wxUser = wxUserService.getOne(qwUser);

        DeviceRange deviceRange = deviceRangeService.findById(deviceId);
        if(deviceRange != null){
            Map<String,Object> mapReturn = deviceRangeRecordService.getChartData(wxUser,deviceRange);
            return R.ok(mapReturn);
        }
        return R.error("设备不存在");
    }

    @Log("测量结果列表")
    @ResponseBody
    @GetMapping("/charts/result/list")
    public DataTableLayUI<DeviceRangeResult> chartsResultList(DataTableLayUI<DeviceRangeResult> condition) {

        UserDO user = getUser();
        QueryWrapper<WxUser> qwUser = new QueryWrapper<>();
        qwUser.eq("sys_user_id",user.getUserId());
        qwUser.eq("platform", "cy");
        qwUser.last("limit 1");
        WxUser wxUser = wxUserService.getOne(qwUser);

        Map<String,Object> map = condition.getSearchParams();

        int deviceId = map.containsKey("search_eq_deviceId")? Integer.parseInt(map.get("search_eq_deviceId").toString()):0;

        QueryWrapper<DeviceRangeResult> qw = new QueryWrapper<>();
        qw.eq("device_id",deviceId);
        if(wxUser!= null){
            if(wxUser.getIsTest() == 0){
                qw.eq("is_test",0);
            }
        }else{
            if(user.getUserType() == 10){
                qw.eq("is_test",0);
            }
        }
        condition.setQw(qw);

        DataTableLayUI<DeviceRangeResult> dt = deviceRangeResultService.pageSearchLayUI(condition);
        List<DeviceRangeResult> devices = dt.getData();
        for (DeviceRangeResult result : devices){
            result.setWeight(MathUtil.getDouble(result.getWeight() / 1000));
            DeviceRange range = deviceRangeService.findById(result.getDeviceId());
            if(range!= null){
                result.setIsShowEmpty(range.getIsShowEmpty());
                result.setIsShowFull(range.getIsShowFull());
            }
        }
        return dt;
    }


    @Log("新增设备页面")
    @GetMapping("/charts/result/{id}")
    String chartsResult(@PathVariable("id") Integer id, Model model) {

        UserDO user = getUser();
        QueryWrapper<WxUser> qw = new QueryWrapper<>();
        qw.eq("sys_user_id",user.getUserId());
        qw.eq("platform", "cy");
        qw.last("limit 1");
        WxUser wxUser = wxUserService.getOne(qw);

        DeviceRange device = deviceRangeService.findById(id);
        if(device != null){
            String beginDate =  DateUtils.getMonthStr(new Date()) + "-01";
            String endDate = DateUtils.getDay();
            Map<String,Object> mapReturn = deviceRangeResultService.getChartDataByDeviceRange(wxUser,user,device,beginDate,endDate);
            model.addAttribute("charts", mapReturn);
        }
        model.addAttribute("device", device);
        return "module/device/range/resultChart";
    }


    @Log("新增设备页面")
    @PostMapping("/charts/result/data")
    @ResponseBody
    R chartsResultData(@RequestParam Map<String,Object> paramJson) {

        UserDO user = getUser();
        QueryWrapper<WxUser> qw = new QueryWrapper<>();
        qw.eq("sys_user_id",user.getUserId());
        qw.eq("platform", "cy");
        qw.last("limit 1");
        WxUser wxUser = wxUserService.getOne(qw);

        int deviceId = Integer.parseInt(paramJson.get("deviceId").toString());
        String beginDate = paramJson.containsKey("begin_date") && StrUtil.isNotEmpty(paramJson.get("begin_date").toString()) ? paramJson.get("begin_date").toString() :  DateUtils.getDay();
        String endDate = paramJson.containsKey("end_date") && StrUtil.isNotEmpty(paramJson.get("end_date").toString()) ? paramJson.get("end_date").toString():  DateUtils.getDay();
        DeviceRange deviceRange = deviceRangeService.findById(deviceId);
        if(deviceRange!= null){
            Map<String,Object> mapReturn = deviceRangeResultService.getChartDataByDeviceRange(wxUser,user,deviceRange,beginDate,endDate);
            return R.ok(mapReturn);
        }
        return R.error("设备不存在");
    }



    @Log("新增设备页面")
    @PostMapping("/charts/result/data3d")
    @ResponseBody
    R chartsResultData3d(Integer resultId) {
//        int resultId = Integer.parseInt(paramJson.get("resultId").toString());
        DeviceRangeResult result = deviceRangeResultService.findById(resultId);
        if(result !=null){
            DeviceRange deviceRange = deviceRangeService.findById(result.getDeviceId());
            if(deviceRange!= null){
                QueryWrapper<DeviceRangeRecord> qwRecord = new QueryWrapper<>();
                qwRecord.eq("device_id", deviceRange.getId());
                qwRecord.eq("data_code", result.getDataCode());
                qwRecord.gt("now_angle", result.getEffectiveAngle());
                qwRecord.orderByAsc("now_angle");
                List<Double> heights = new ArrayList<>();
                List<DeviceRangeRecord> records = deviceRangeRecordService.list(qwRecord);
                if(CollUtil.isNotEmpty(records)){
                    for (DeviceRangeRecord record : records){
                        heights.add(record.getNowHeight());
                    }
                }
                Map<String,Object> map = new HashMap<>();
                map.put("records",heights);
                return R.ok(map);
            }
        }
        return R.error("暂无数据");
    }


    @GetMapping("/result/record/exportExcel")
    public void testExportExcel(@RequestParam("begin_date") String begin_date, @RequestParam("end_date") String end_date,
                                @RequestParam("deviceId") String deviceId, HttpServletResponse response){
//        UserDO user = getUser();
//        Map<String,Object> map = new HashMap<>();
//        if(StrUtil.isNotEmpty(begin_date) && StrUtil.isNotEmpty(end_date)){
//            map.put("begin_time",begin_date +" 00:00:00");
//            map.put("end_time", end_date +" 23:59:59");
//        }else{
//
//        }
        String shopName = "";
        String deviceNum = "";
        DeviceRange deviceRange = deviceRangeService.findById(deviceId);
        if(deviceRange!= null){
            deviceNum = deviceRange.getDeviceNum();
            Shop shop = shopService.findById(deviceRange.getShopId());
            if(shop!= null){
                shopName = shop.getShopName();
            }
        }
        QueryWrapper<DeviceRangeResult> qw = new QueryWrapper<>();
        qw.eq("device_id",deviceId);
        if(StrUtil.isNotEmpty(begin_date) && StrUtil.isNotEmpty(end_date)){
            qw.between("create_time",begin_date +" 00:00:00",end_date +" 23:59:59");
        }else{
            begin_date = DateUtils.getMonthStr(new Date()) + "-01";
            end_date = DateUtils.getDay();
            qw.between("create_time",begin_date +" 00:00:00",end_date +" 23:59:59");
        }
        qw.orderByAsc("create_time");
        List<DeviceRangeResult> records = deviceRangeResultService.list(qw);

        String finalShopName = shopName;
        records.forEach(record->{
            record.setShopName(finalShopName);
            record.setCreateTimeStr(DateUtils.getTime(record.getCreateTime()));
            if(StrUtil.isNotEmpty(record.getTemperature()) && !record.getTemperature().equals("0")){
                record.setTemperature(Integer.parseInt(record.getTemperature())+ "℃");
            }
            if(record.getDeviceType() == 0){
                record.setWeightDun(MathUtil.getDoubleUpThree(record.getWeight() / 1000) + "吨");
            }else{
                record.setWeightDun(record.getWeight() + "吨");
            }
        });

        ExcelUtils.writeExcel(response, records, DeviceRangeResult.class, deviceNum + "_" + System.currentTimeMillis() + "_测量结果.xlsx");
    }


    /**
     * 开始测量
     */
    @Log("开始测量")
    @PostMapping("/measure")
    @ResponseBody
    public R measure(Integer id) {
        UserDO user = getUser();
        int wxUserId = 0;
        QueryWrapper<WxUser> qw = new QueryWrapper<>();
        qw.eq("sys_user_id",user.getUserId());
        qw.eq("platform", "cy");
        qw.last("limit 1");
        WxUser wxUser = wxUserService.getOne(qw);
        if(wxUser!= null){
            wxUserId = wxUser.getId();
        }
        String url = "https://en.zcchengyi.com/ckapi/device/startMeasure";
        DeviceRange deviceRange = deviceRangeService.findById(id);
        if(deviceRange != null){
            String data = "{\"user_id\":"+wxUserId+",\"sn\":\""+deviceRange.getDeviceNum()+"\",\"order\":\"04\",\"data\":\"01\",\"device_id\":"+deviceRange.getId()+"}";
            if(deviceRange.getDeviceType() == 1){
                data = "{\"user_id\":"+wxUserId+",\"sn\":\""+deviceRange.getDeviceNum()+"\",\"order\":\"06\",\"data\":\"01\",\"device_id\":"+deviceRange.getId()+"}";
            }
            try {
                String ret = OkHttpClientUtil.getInstance().postJson(url, data);
                System.out.println("测量响应：" + ret);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return R.ok();
    }
}
